#!/bin/sh

# --------config---------
TUNDEVICENAME=vethenp
PROGRAMNAME=system-n2n-v-2-6
PROGRAMCONF=system-n2n.conf
PID=""
IP=10.234.233.1
# --------config---------

BASE_DIR=$(
  cd "$(dirname "$0")" || exit
  pwd
)

if [ "$(id -u)" -eq 0 ]; then
  echo "$(date +%Y-%m-%d\ %H:%M:%S) root用户!"
else
  echo "$(date +%Y-%m-%d\ %H:%M:%S) 非root用户!"
  exit 0
fi

PROGRAMPATH=${BASE_DIR}/${PROGRAMNAME}
CONFPATH=${BASE_DIR}/${PROGRAMCONF}
STARTCMD="$PROGRAMPATH $CONFPATH"

checkNetworkExists() {
  if ifconfig | grep $TUNDEVICENAME >/dev/null; then
    echo "$(date +%Y-%m-%d\ %H:%M:%S) found $TUNDEVICENAME"
    return 0
  else
    echo "$(date +%Y-%m-%d\ %H:%M:%S) not found NetWork"
    return 1
  fi
}

checkPing() {
  total="0"
  i="0"
  echo "$(date +%Y-%m-%d\ %H:%M:%S) start ping $IP !"
  while [ $i -lt 10 ]; do
    line=""
    line=$(ping $IP -c 1 -s 1 -W 1 | grep -c "100% packet loss")
    if [ "${line}" != "0" ]; then
      total=$((total + 1))
    else
      total="0"
    fi
    i=$((i + 1))
    sleep 1
  done
  if [ $total -gt 5 ]; then
    echo "$(date +%Y-%m-%d\ %H:%M:%S) check $IP failed!"
    return 1
  else
    echo "$(date +%Y-%m-%d\ %H:%M:%S) check $IP ok!"
    return 0
  fi
}

checkProcess() {
  PID=$(pgrep -f "$STARTCMD")
  if [ "$PID" != "" ]; then
    echo "$(date +%Y-%m-%d\ %H:%M:%S) checkProcess found pid $PID"
    return 0
  else
    echo "$(date +%Y-%m-%d\ %H:%M:%S) checkProcess not found PID"
    return 1
  fi
}

killProcess() {
  kill -9 "$PID"
  echo "$(date +%Y-%m-%d\ %H:%M:%S) kill Process $PID"
}

startProcess() {
  $STARTCMD >/tmp/$PROGRAMNAME.log 2>&1 &
  sleep 1s
  cat /tmp/$PROGRAMNAME.log
  echo "$(date +%Y-%m-%d\ %H:%M:%S) startProcess"
}

main() {
  while true; do
    echo "$(date +%Y-%m-%d\ %H:%M:%S) runing..."
    if checkProcess; then

      if checkPing; then
        echo "$(date +%Y-%m-%d\ %H:%M:%S) ok"
      else
        killProcess
        startProcess
      fi

    else

      startProcess
    fi

    sleep 180s
  done
}

main
